import json

from django.contrib.auth.models import User
from django.core.paginator import Paginator
from django.http.response import JsonResponse, HttpResponseForbidden
from django.shortcuts import render, redirect

from res.models import Resource
from user.models import UserInfo

from user.models import UserScore
from django.db.models import Subquery, OuterRef, F, Sum
from message.models import Fans
from LoveDownload.db import DBUtils



def personal(request):
    """个人信息"""
    if request.method == 'GET':
        # 匿名用户需要登录
        if request.user.is_anonymous:
            return redirect('login')

    #查询用户粉丝数 和关注数
    sql="""
    select sum(fans) fans,sum(attach) attach from (
    select count(1) fans ,'' attach from tb_fans where user_id=%s
    union all
    select count(1) ,'' from tb_fans where fans_id=%s and is_mutual=1
    union all
    select '' fans,count(1) attach from tb_fans where fans_id=%s
    union all
    select '',count(1) from tb_fans where user_id=%s and is_mutual=1
    ) t
    """

    user_id=request.user.id
    data=DBUtils.select_one(sql,[user_id]*4)


    #查询用户 基本信息
    info = UserInfo.objects.filter(user=request.user).select_related("user").first()

    # 查询用户的所有积分
    user_score=UserScore.objects.filter(user=request.user).values(name=F('remark')).annotate(value=Sum('score'))

    # 查询用户积分 和对应的资源名称 添加计算字段
    scores = (UserScore.objects.filter(user_id=request.user.id).annotate
              (resource_name=Subquery(Resource.objects.filter(pk=OuterRef("res_id")).values('name')[:1])))

    return render(request, 'personal.html',
                  context={'info': info,'user_score': list(user_score),'score_details':scores,
                           "fans_attach":data})

def score_list(request):
    """积分明细列表"""
    #总页数，每页显示条数
    page_number=int(request.GET.get('page',1))
    row=int(request.GET.get('row',10))

    # 查询用户积分 和对应的资源名称
    queryset=(UserScore.objects.filter(user=request.user).annotate
              (resource_name=Subquery(Resource.objects.filter(pk=OuterRef("res_id")).values('name')[:1]))).order_by("-pk")

    #进行分页查询
    paginator=Paginator(queryset, row)
    page=paginator.get_page(page_number)
    data=list(page.object_list.values("resource_name","score","remark","create_time","res_id"))

    #满足条件的 总页数
    pages=page.paginator.num_pages

    return JsonResponse({"code":200,"list":data,"pages":pages})

def modify_nickname(request):
    """修改昵称"""
    if request.method == 'POST':
        nickname = request.POST.get('nickname')
        user_id = request.user.pk

        UserInfo.objects.filter(user_id=user_id).update(nickname=nickname)

        return JsonResponse({"code": 200,"msg":"修改成功"})
    return JsonResponse({"code": 400,"msg":"修改失败"})

def modify_sex(request):
    """修改性别"""

    if request.method == 'POST':
        sex = request.POST.get('sex')

        user_id = request.user.pk

        UserInfo.objects.filter(user_id=user_id).update(gender=sex)

        return JsonResponse({"code": 200,"msg":"修改成功"})

    return JsonResponse({"code": 400,"msg":"修改失败"})


def attention(request):
    """关注人员列表"""
    return render(request,'attention.html')




